package myJs.user.data

import myJs.Implicits._
import myJs.Utils._
import scala.scalajs.js.Dynamic.{global => g}
import myJs.myPkg.bootstrap.Bootstrap.default._
import myJs.myPkg.jquery._
import myJs.myPkg.{LayerOptions, Select2Options}
import myJs.tool.Tool
import org.scalajs.dom.{Element, document}
import shared.Pojo.VarInfoDataKind
import myJs.tool.Tool._

import scala.scalajs.js
import scala.scalajs.js.JSConverters._

/**
 * Created by yz on 10/11/2020
 */
object ExtraVarInfoModal {

  val modalId = "extraVarInfoModal"
  val formId = "subForm"
  var fileData: JDJAn = _

  def init = {
    bootStrapValidator
    registerEvent
  }

  def registerEvent = {
    $(document.body).on("click", ".myExtraVarInfo", "", (y: Element) => {
      extraVarInfo
    })
    $(document.body).on("change", s"#${modalId} .mySelectColumn", "", (y: Element) => {
      selectColumnChange(y)
    })
  }

  def selectColumnChange(y: Element) = {
    val myValue = $(y).find(">option:selected").`val`().toString
    val values = fileData("array").toJArJDS.map { dict =>
      dict(myValue)
    }.distinct
    val jq = $(s"#${modalId}").findInputByName("selectGroup")
    if (myValue == "Metabolite") {
      jq.parents(".form-group").hide()
    } else {
      val array = (values).map { v =>
        js.Dictionary("text" -> v, "id" -> v)
      }
      val options = Select2Options(data = array.toJSArray, multiple = true, placeholder = messages("clickToChoose"))
      jq.mySelect2(options)
      jq.parents(".form-group").show()
    }
  }

  def extraVarInfoForm = {
    $(s"#${modalId} #${formId}")
  }

  def extraVarInfo = {
    val bv = extraVarInfoForm.bv
    bv.validate()
    val valid = bv.isValid()
    if (valid) {
      val selectColumn = extraVarInfoForm.findInputByName("selectColumn").myVal
      val array = fileData("array").toJArJDS
      val filterArray = if (selectColumn == "Metabolite") {
        array
      } else {
        val selectGroups = extraVarInfoForm.findInputByName("selectGroup").select2Val
        array.filter { dict =>
          selectGroups.contains(dict(selectColumn))
        }
      }
      val metabolites = filterArray.map { dict =>
        dict("Metabolite")
      }.toList
      SubModal.leftMoves(metabolites)
      $(s"#${modalId}").modal("hide")
    }
  }

  def fileSelect(folder: String, fileName: String) = {
    val fileModalId = "fileModal"
    val inputJq = $(".myFileSelect.myCurrent").parent().prev().find("input")
    inputJq.`val`(s"${folder}/${fileName}")
    $(s"#${modalId} #${formId}").bv.revalidateField(inputJq)
    refreshFileData
    refreshSelectColumn
    $(s"#${fileModalId}").modal("hide")
  }

  def refreshSelectColumn = {
    val columnNames = fileData("columnNames").toJArS
    val array = (columnNames).map { v =>
      js.Dictionary("text" -> v, "id" -> v)
    }
    val options = Select2Options(data = array.toJSArray)
    val jq = $(s"#${modalId}").findInputByName("selectColumn")
    jq.mySelect2(options)
    jq.`val`("Metabolite").trigger("change")
    jq.parents(".form-group").show()
  }

  def refreshFileData = {
    val fileName = Tool.getInputByName("varInfoFile").myVal
    val url = g.jsRoutes.controllers.DataController.getFileDataByFileName().url.toString
    val ajaxSettings = JQueryAjaxSettings.url(s"${url.noCache}&fileName=${fileName.encodeURI}").async(false).`type`("get").
      success { (data: js.Any, status: String, e: JQueryXHR) =>
        val rs = data.toJDJAn
        fileData = rs
      }
    $.ajax(ajaxSettings)
  }

  def bootStrapValidator = {
    val maxNumber = Double.MaxValue
    val dict: js.Dictionary[js.Any] = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
        "varInfoFile" -> {
          val info = messages("varInfoFile")
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${messages("null")}"
              ),
              "remote" -> js.Dictionary(
                "message" -> s"${messages("notExist")}",
                "url" -> Tool.fileNameCheckUrl,
                "type" -> "POST",
                "delay" -> 1000,
                "name" -> "fileName",
              ),
            )
          )
        },
        "selectGroup" -> {
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${messages("null")}"
              ),
            )
          )
        },
      )
    )
    $(s"#${modalId} #${formId}").bootstrapValidator(dict)
  }


}
